package cn.demo.client.api;


import cn.demo.common.core.controller.BaseController;
import cn.demo.common.core.domain.R;
import cn.demo.common.core.domain.entity.SysDept;
import cn.demo.common.core.page.PageQuery;
import cn.demo.common.core.page.PageR;
import cn.demo.common.exception.ServiceException;
import cn.demo.common.utils.*;
import cn.demo.sys.service.ISysDeptService;
import cn.demo.um.domain.UmAttrConf;
import cn.demo.um.domain.UmClientUser;
import cn.demo.um.domain.UmUserFocus;
import cn.demo.um.domain.UmWeddingGift;
import cn.demo.um.service.IUmAttrConfService;
import cn.demo.um.service.IUmClientUserService;
import cn.demo.um.service.IUmUserFocusService;
import cn.demo.um.service.IUmWeddingGiftService;
import cn.demo.weixin.ma.constant.WxMaConstants;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author xtjun
 * @description 用户api
 * @date 2024/06/04
 */
@Tag(name = "用户api")
@RestController
@RequestMapping("/api/um")
public class UmApi extends BaseController {

    @Resource
    IUmClientUserService clientUserService;

    @Resource
    IUmUserFocusService umUserFocusService;

    @Resource
    ISysDeptService sysDeptService;

    @Resource
    IUmAttrConfService umAttrConfService;

    @Resource
    IUmWeddingGiftService umWeddingGiftService;

    @Operation(summary = "查询客户端用户列表")
    @GetMapping("/list")
    public PageR<UmClientUser> list(UmClientUser umClientUser, PageQuery pageQuery) {
        String deptId = ServletUtils.getHeader(WxMaConstants.HEADER_DEPT_ID);
        if (StringUtils.isNotEmpty(deptId)) {
            umClientUser.setDeptId(deptId);
        }
        umClientUser.setAuthStatus(9);
        Page<UmClientUser> page = clientUserService.selectUmClientUserPage(umClientUser, pageQuery);
        buildUser(page);
        return PageR.ok(page);
    }

//    @Operation(summary = "查询客户端用户列表")
//    @GetMapping("/list")
//    public PageR<UmClientUser> list(PageQuery pageQuery) {
//        SecurityUtils.getUserId()
//        String deptId = ServletUtils.getHeader(WxMaConstants.HEADER_DEPT_ID);
//        if (StringUtils.isNotEmpty(deptId)) {
//            umClientUser.setDeptId(deptId);
//        }
//        umClientUser.setAuthStatus(9);
//        Page<UmClientUser> page = clientUserService.selectUmClientUserPage(umClientUser, pageQuery);
//        buildUser(page);
//        return PageR.ok(page);
//    }

    @Operation(summary = "查询用户详情")
    @GetMapping("/getInfo")
    public R<UmClientUser> getInfo() {
        UmClientUser user = getUmClientUser(SecurityUtils.getUserId());
        return R.ok(user);
    }

    @Operation(summary = "查询用户详情")
    @GetMapping("/info/{id}")
    public R<UmClientUser> info(@PathVariable("id") String id) {
        UmClientUser user = getUmClientUser(id);
        return R.ok(user);
    }

    @Operation(summary = "修改用户信息")
    @PutMapping("/updateInfo")
    public R edit(@RequestBody UmClientUser umClientUser) {
        if (!umClientUser.getId().equals(SecurityUtils.getUserId())) {
            throw new ServiceException("只能修改自己的信息");
        }
        return toAjax(clientUserService.updateUmClientUser(umClientUser));
    }

    private UmClientUser getUmClientUser(String id) {
        UmClientUser user = clientUserService.selectUserVoById(id);
        setDept(user);
        setFocus(user);
        return user;
    }



    @Operation(summary = "关注用户")
    @GetMapping("/focus/{id}")
    public R focus(@PathVariable("id") String id) {
        return toAjax(clientUserService.focus(id));
    }

    @Operation(summary = "取消关注用户")
    @GetMapping("/focusCancel/{id}")
    public R focusCancel(@PathVariable("id") String id) {
        return toAjax(clientUserService.focusCancel(id));
    }

    @Operation(summary = "关注统计")
    @GetMapping("/focusCount")
    public R<Map<Object, Object>> focusCount() {
        return R.ok(clientUserService.focusCount(SecurityUtils.getUserId()));
    }

    @Operation(summary = "关注列表")
    @GetMapping("/focusList")
    @Parameters({
            @Parameter(name = "type", description = "类型", required = true),
            @Parameter(name = "key", description = "搜索字段")
    })
    public PageR<UmClientUser> focusList(String key, String type, PageQuery pageQuery) {
        Page<UmClientUser> page = clientUserService.focusList(SecurityUtils.getUserId(), key, type, pageQuery);
        buildUser(page);
        return PageR.ok(page);
    }

    @Operation(summary = "查询用户属性配置列表")
    @GetMapping("/attrConfList")
    public R<List<UmAttrConf>> list() {
        return R.ok(umAttrConfService.selectUmAttrConfAll());
    }

    @Operation(summary = "提交登记领证")
    @PostMapping("/addWeddingGift")
    public R add(@RequestBody @Validated UmWeddingGift umWeddingGift) {
        UmWeddingGift gift = umWeddingGiftService.getOne(QueryWrapper.create().eq(UmWeddingGift::getUserId, SecurityUtils.getUserId()));
        if (null != gift){
            throw new ServiceException("您已经提交申请，请勿重复提交");
        }
        umWeddingGift.setUserId(SecurityUtils.getUserId());
        umWeddingGift.setStatus(0);
        return toAjax(umWeddingGiftService.insertUmWeddingGift(umWeddingGift));
    }

    @Operation(summary = "查询登记领证信息")
    @GetMapping("/getWeddingGift")
    public R<UmWeddingGift> add() {
        return R.ok(umWeddingGiftService.getOne(QueryWrapper.create().eq(UmWeddingGift::getUserId,SecurityUtils.getUserId())));
    }

    private void buildUser(Page<UmClientUser> page) {
        if (CollectionUtils.isNotEmpty(page.getRecords())) {

            Set<String> uIds = page.getRecords().stream().map(UmClientUser::getId).collect(Collectors.toSet());
            Map<String, UmUserFocus> focusMap = umUserFocusService.list(QueryWrapper.create().eq(UmUserFocus::getUserId, SecurityUtils.getUserId()).in(UmUserFocus::getFocusId, uIds)).stream().collect(Collectors.toMap(UmUserFocus::getFocusId, Function.identity()));

            page.getRecords().forEach(user -> {
                user.setIsFocus(ObjUtils.isNotEmpty(focusMap.get(user.getId())));
                setDept(user);
            });
            clientUserService.buildDict(page.getRecords());
        }
    }

    private void setDept(UmClientUser user) {
        if (StringUtils.isNotEmpty(user.getDeptId())){
            SysDept sysDept = sysDeptService.selectDeptById(user.getDeptId());
            if (null != sysDept){
                sysDept.setParentName(sysDeptService.getDeptParentName(user.getDeptId()));
            }
            user.setDeptInfo(sysDept);
        }
    }

    private void setFocus(UmClientUser user) {
        String myId = SecurityUtils.getUserId();
        String otherId = user.getId();
        if (otherId.equals(myId)){
            user.setIsFocus(true);
            user.setIsFocusEachOther(true);
        }else {
            long l1 = umUserFocusService.count(QueryWrapper.create().eq(UmUserFocus::getUserId, myId).eq(UmUserFocus::getFocusId, otherId));
            long l2 = umUserFocusService.count(QueryWrapper.create().eq(UmUserFocus::getUserId, otherId).eq(UmUserFocus::getFocusId, myId));
            user.setIsFocus(l1 > 0);
            user.setIsFocusEachOther(l1 > 0 && l2 > 0);
        }
    }


}
